package cn.swanit.common.base.handler;

import cn.swanit.common.base.Result;
import cn.swanit.common.base.annotation.NoResult;
import cn.swanit.common.base.enums.IotCloudEnum;
import cn.swanit.common.base.exception.IotCloudException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@Slf4j
@RestControllerAdvice(annotations = RestController.class)
public class ResponseControllerAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> aClass) {
        NoResult noResult = returnType.getMethodAnnotation(NoResult.class);
        if (noResult != null) {
            return false;
        }
        // 如果接口返回的类型本身就是Result那就没有必要进行额外的操作，返回false
        Class<?> parameterType = returnType.getParameterType();
        log.info("ResponseControllerAdvice===parameterType=={}", parameterType);
        if (parameterType.equals(ResponseEntity.class)) {
            return false;
        }
        if (parameterType.toString().toUpperCase().endsWith("DTO")) {
            return false;
        }
        return !parameterType.equals(Result.class);
    }

    @Override
    public Object beforeBodyWrite(Object data, MethodParameter returnType, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest request, ServerHttpResponse response) {
        if (returnType.getGenericParameterType().equals(String.class)) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                // 将数据包装在ResultVO里后，再转换为json字符串响应给前端
                return objectMapper.writeValueAsString(Result.ok(data));
            } catch (JsonProcessingException e) {
                throw new IotCloudException(IotCloudEnum.SYS_2000001);
            }
        }
        return Result.ok(data);
    }
}